import { useState, useEffect } from 'react';
import { Modal, Table, Card, Statistic, Row, Col, Empty } from 'antd';
import { get } from '../services/api';

function StudentGradeModal({ visible, onClose, studentInfo }) {
  const [grades, setGrades] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (visible && studentInfo) {
      fetchStudentGrades();
    }
  }, [visible, studentInfo]);

  const fetchStudentGrades = async () => {
    setLoading(true);
    try {
      const response = await get(`grades/students/${studentInfo.student_id}`);
      setGrades(response.data || response);
    } catch (error) {
      console.error('获取学生成绩失败:', error);
      setGrades([]);
    } finally {
      setLoading(false);
    }
  };

  // 计算统计信息
  const calculateStats = () => {
    if (!grades.length) return { avg: 0, max: 0, min: 0, total: 0, passed: 0 };
    
    const scores = grades.map(g => g.grade);
    const total = grades.length;
    const passed = scores.filter(score => score >= 60).length;
    const avg = scores.reduce((sum, score) => sum + score, 0) / total;
    const max = Math.max(...scores);
    const min = Math.min(...scores);
    
    return { avg: avg.toFixed(1), max, min, total, passed };
  };

  const stats = calculateStats();

  const columns = [
    {
      title: '课程名称',
      dataIndex: 'course_name',
      key: 'course_name',
      width: '25%',
    },
    {
      title: '班级',
      dataIndex: 'class_name',
      key: 'class_name',
      width: '20%',
    },
    {
      title: '学期',
      dataIndex: 'semester',
      key: 'semester',
      width: '20%',
    },
    {
      title: '成绩',
      dataIndex: 'grade',
      key: 'grade',
      width: '15%',
      render: (grade) => {
        let color = '#f5222d'; // 不及格红色
        if (grade >= 90) color = '#52c41a'; // 优秀绿色
        else if (grade >= 80) color = '#1890ff'; // 良好蓝色
        else if (grade >= 70) color = '#faad14'; // 中等黄色
        else if (grade >= 60) color = '#fa8c16'; // 及格橙色
        
        return <span style={{ color, fontWeight: 'bold' }}>{grade}</span>;
      }
    },
    {
      title: '等级',
      dataIndex: 'grade',
      key: 'level',
      width: '20%',
      render: (grade) => {
        if (grade >= 90) return <span style={{ color: '#52c41a' }}>优秀</span>;
        if (grade >= 80) return <span style={{ color: '#1890ff' }}>良好</span>;
        if (grade >= 70) return <span style={{ color: '#faad14' }}>中等</span>;
        if (grade >= 60) return <span style={{ color: '#fa8c16' }}>及格</span>;
        return <span style={{ color: '#f5222d' }}>不及格</span>;
      }
    },
  ];

  return (
    <Modal
      title={`学生成绩报表 - ${studentInfo?.student_name} (${studentInfo?.student_id})`}
      open={visible}
      onCancel={onClose}
      footer={null}
      width={900}
      style={{ top: 20 }}
    >
      <div style={{ marginBottom: 24 }}>
        {/* 统计信息卡片 */}
        <Card title="成绩统计" style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={4}>
              <Statistic title="总科目" value={stats.total} />
            </Col>
            <Col span={4}>
              <Statistic title="及格科目" value={stats.passed} />
            </Col>
            <Col span={4}>
              <Statistic 
                title="及格率" 
                value={stats.total > 0 ? ((stats.passed / stats.total) * 100).toFixed(1) : 0} 
                suffix="%" 
              />
            </Col>
            <Col span={4}>
              <Statistic title="平均分" value={stats.avg} precision={1} />
            </Col>
            <Col span={4}>
              <Statistic title="最高分" value={stats.max} />
            </Col>
            <Col span={4}>
              <Statistic title="最低分" value={stats.min} />
            </Col>
          </Row>
        </Card>

        {/* 成绩详情表格 */}
        <Card title="成绩详情">
          {grades.length > 0 ? (
            <Table
              columns={columns}
              dataSource={grades}
              rowKey={(record) => `${record.class_id}_${record.course_name}`}
              loading={loading}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
              size="middle"
            />
          ) : (
            <Empty description="暂无成绩记录" />
          )}
        </Card>
      </div>
    </Modal>
  );
}

export default StudentGradeModal;